//
//  WWRefreshControl.swift
//  Microblog
//
//  Created by steaest on 15/8/10.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit

private let kRefreshPullOffset: CGFloat = -50

//MARK: - 下拉刷新控件,集成在 tableView Controller
class WWRefreshControl: UIRefreshControl {
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    //MARK: - KVO
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        //是否刷新的状态
        if refreshing {
            refreshView.startloading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag{
            refreshView.rotateFlag = false
        }
        
    }

    //MARK: - 构造函数
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 销毁kvo监听
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    //MARK: - 设置界面
    private func setupUI() {
        //MARK: - kvo监听
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        //隐藏转轮
        tintColor = UIColor.clearColor()
        //添加
        addSubview(refreshView)
        
        //print(refreshView.bounds.size)
        //自动布局 - 从 xib 加载的时候,可以直接获取到真实的大小
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }

    //MARK: - 懒加载控件
    private lazy var refreshView: WWRefreshView = WWRefreshView.refreshView()
}

//MARK: - 下拉刷新视图 - 负责显示和动画
class WWRefreshView: UIView {
    //MARK: - 是否旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIcon: UIImageView!
    //MARK: - 提供类方法,从xib加载视图
    class func refreshView() -> WWRefreshView {
        return NSBundle.mainBundle().loadNibNamed("WWRefreshView", owner: nil, options: nil).last as! WWRefreshView
    }
    //MARK: - 提示图标旋转
    private func rotateTipIcon() {
        //块代码执行动画,就近原则,所以要少一点点
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    //MARK: - 添加动画
    private func startloading() {
        tipView.hidden = true
        //0,使用关键字让动画不重复加载
        if loadingIcon.layer.animationForKey("loadingAnim") != nil {
            return
        }
    
        //添加动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        //设置动画属性
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1
        
        //添加到视图(设有关键字)
        loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
        
    }
    
    //MARK: - 停止加载动画
    private func stopLoading() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
}